#pragma once
#include<iostream>
using namespace std;

template<class K>
struct BSTreeNode
{
	K _key;
	BSTreeNode<K>* _left;
	BSTreeNode<K>* _right;

	BSTreeNode(K key)
		:_key(K)
		,_left(nullptr)
		,_right(nullptr)
	{}
};

template<class K>
class BSTree
{
	typedef BSTreeNode<K> Node;
public:
	BSTree(initializer_list<K> il)
	{
		for (auto& x : il)
		{
			insert(x);
		}
	}

	bool insert(const K& key) 
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}
		
		Node* parent = _root;
		Node* cur = _root;

		while (cur)
		{
			if (key > cur->_key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if(key < cur->_key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		
		if (key > parent->_key)
		{
			parent->_right = new Node(key);
		}
		else
		{
			parent->_left = new Node(key);
		}
		return true;
	}

	bool erase(const K& key)
	{
		if (_root == nullptr)
		{
			return false;
		}

		Node* parent = _root;
		Node* cur = _root;
		while (cur)
		{
			if (key > cur->_key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (key < cur->_key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_left;
					}
					else
					{
						if (key > parent->_key)
						{
							parent->_right = cur->_right;
						}
						else
						{
							parent->left = cur->_right;
						}
					}
					delete cur;
					return true;
				}
				else if (cur->_right == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_right;
					}
					else
					{
						if (key > parent->_key)
						{
							parent->_right = cur->_left;
						}
						else
						{
							parent->left = cur->_left;
						}
					}
					delete cur;
					return true;
				}
				else
				{
					Node* maxleft = cur->left;
					Node* maxleftParent = cur;
					while (maxleft->_right)
					{
						maxleftParent = maxleft;
						maxleft = maxleft->_right;
					}
					cur->_key = maxleft->_key;
					

					if (key > maxleftParent->_key)
					{
						maxleftParent->_right = maxleft->_left;
					}
					else
					{
						maxleftParent->_left = maxleft->_left;
					}
				}
				return true;
			}
			return false;
		}
	}

	bool find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (key > cur->_key)
			{
				cur = cur->_right;
			}
			else if (key < cur->_key)
			{
				cur = cur->_left;
			}
			else
			{
				return true;
			}
		}
		return false;
	}

	void Inorder()
	{
		_Inorder(_root);
		cout << endl;
	}
private:
	void _Inorder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		_Inorder(root->_left);
		cout << root->_key << ' ';
		_Inorder(root->_rgiht);
	}

	Node* _root = nullptr;
};